<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 客户端用户登录
 *
 * @author      Eden
 * @datetime    2016/11/30 21:33
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Login_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run(Array $params)
    {
        $send['state'] = false;
        do {

            if (!$this->_checkParams($params)) {
               $send['error'] = $this->getError();
               break;
            }

            if ($user = $this->_checkUserAndStatus($params['phone'])) {

                $password = $user['password'];
                $salt = $user['salt'];

                if (!decryptPassword($params['password'], $password, $salt)) {
                    $send['error'] = '用户名或密码错误';
                    break;
                } else {

                    $profile = $this->_getProfile($user['id']);
                    if (empty($profile)) {
                        $send['error'] = '用户数据错误';
                        break;
                    }

                    // 记录手机登录状态
                    $this->saveLoginStatus($user['id'], $params);

                    // 修改最后登录时间
                    $this->_modifyLastLoginInfo($user);

                    // 查 purchaser_apply表
                    $p = $this->getPurchaser($user['id']);
                    if (empty($p)) {
                        $purchaser = 0;
                    } elseif ($p['status'] == 5) {
                        $purchaser = 5;
                    } elseif ($p['status'] == 0) {
                        $purchaser = 3;
                    } else {
                        $purchaser = 6;
                    }

                    $send['state'] = true;
                    $send['data'] = array(
                        'userId' => (int) value($user, 'id'),
                        'nickName' => value($user, 'nickName'),
                        'trueName' => value($profile, 'trueName'),
                        'phone' => value($user, 'phone'),
                        'avatar' => thumb($profile['avatar'], 100, 100),
                        'lastIp' => value($user, 'lastIp'),
                        'lastTime' => value($user, 'lastTime'),
                        'status' => intval($user['status']),
                        'purchaser' => intval($purchaser),
                    );
                }
            } else {
                $send['error'] = $this->getError();
                break;
            }


        } while(0);
        $this->output->send($send);
    }

    /**
     * 获取采购商申请记录
     * @param $userId
     * @return mixed
     */
    public function getPurchaser($userId)
    {
        $db = clone($this->db);
        $query = $db->get_where('purchaser_apply', ['userid' => $userId]);
        return $query->row_array();
    }

    /**
     * 保存登录状态
     * @param $userId
     * @param array $params
     */
    private function saveLoginStatus($userId, $params = array())
    {
        try {
            $loginQuery = $this->db->get_where('user_mobile_login', array('deviceId' => $params['deviceId']));
            if ($loginQuery->row_array()) {
                $this->db->where('deviceId', $params['deviceId']);
                $this->db->update('user_mobile_login', array(
                    'userId' => $userId,
                    'loginTime' => dateTime()
                ));
            } else {
                $this->db->insert('user_mobile_login', array(
                    'userId' => $userId,
                    'loginTime' => dateTime(),
                    'deviceId' => $params['deviceId'],
                    'type' => value($params, 'type')
                ));
            }
        } catch(PDOException $e) {}
    }

    private function _getProfile($id)
    {
        $query = $this->db->get_where('user_profile', array('userId' => $id));
        return $query->row_array();
    }

    /**
     * 修改用户最后登录状态
     * @param $params
     */
    private function _modifyLastLoginInfo($params)
    {
        $userId = value($params, 'id');
        $this->db->where('id', $userId);
        $data = array(
            'lastIp' => remoteAddr(),
            'lastTime' => date('Y-m-d H:i:s')
        );
        $this->db->update('user', $data);
    }

    /**
     * 获取用户信息
     * @param $phone
     * @return mixed
     */
    private function _checkUserAndStatus($phone)
    {
        $query = $this->db->get_where('user', array('phone' => $phone));
        $row = $query->row_array();

        if (!$row) {
            $this->setError('用户名或密码错误');
            return false;
        }

        if ($row['status'] != 1) {
            $this->setError('用户被限制登录');
            return false;
        }

        return $row;
    }

    /**
     * 检查参数
     * @param $params
     * @return bool
     */
    private function _checkParams($params)
    {
        if ($this->input->method(true) !== 'POST') {
            // $this->setError('非法请求');
            // return false;
        }

        if (empty($params['phone']) || empty($params['password']) || empty($params['deviceId'])) {
            $this->setError('参数错误');
            return false;
        }

        return true;
    }
}
